const WEB_SOCKET_URL = "wss://cong.yuyoupx.com/ws"
// const WEB_SOCKET_URL = "ws://localhost:3000"
let ws = null


/**
 * 基于Promise的AJAX请求函数
 * @param {Object} options 配置对象
 * @param {String} options.url 请求URL
 * @param {String} [options.method='GET'] 请求方法 GET/POST
 * @param {Object} [options.data={}] 请求参数
 * @param {Object} [options.headers={}] 请求头
 * @param {Number} [options.timeout=10000] 超时时间(ms)
 * @returns {Promise} Promise对象
 */
const request = (options) => {
    return new Promise((resolve, reject) => {
        // 参数校验
        if (!options || !options.url) {
            reject(new Error('URL参数不能为空'));
            return;
        }

        // 默认配置
        const config = {
            method: (options.method || 'GET').toUpperCase(),
            url: options.url,
            data: options.data || {},
            headers: options.headers || {},
            timeout: options.timeout || 10000
        };

        // 创建XMLHttpRequest对象
        let xhr;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        } else {
            reject(new Error('浏览器不支持XMLHttpRequest'));
            return;
        }

        // 处理请求数据
        let requestData = '';
        if (config.data && Object.keys(config.data).length > 0) {
            if (config.method === 'GET') {
                // GET请求参数拼接到URL
                const params = new URLSearchParams();
                for (let key in config.data) {
                    params.append(key, config.data[key]);
                }
                config.url += '?' + params.toString();
            } else {
                // POST请求参数格式化
                requestData = JSON.stringify(config.data);
                config.headers['Content-Type'] = 'application/json';
            }
        }

        // 设置超时
        const timeoutId = setTimeout(() => {
            xhr.abort();
            reject(new Error('请求超时'));
        }, config.timeout);

        // 初始化请求
        xhr.open(config.method, config.url, true);

        // 设置请求头
        for (let header in config.headers) {
            xhr.setRequestHeader(header, config.headers[header]);
        }

        // 处理响应
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                clearTimeout(timeoutId);

                if (xhr.status === 200) {
                    try {
                        const response = xhr.responseText;
                        // 尝试解析JSON，如果不是JSON则返回原始文本
                        const data = response ? JSON.parse(response) : null;
                        resolve({
                            data: data,
                            status: xhr.status,
                            statusText: xhr.statusText,
                            xhr: xhr
                        });
                    } catch (e) {
                        resolve({
                            data: xhr.responseText,
                            status: xhr.status,
                            statusText: xhr.statusText,
                            xhr: xhr
                        });
                    }
                } else {
                    reject(new Error(`请求失败: ${xhr.status} ${xhr.statusText}`));
                }
            }
        };

        // 错误处理
        xhr.onerror = function () {
            clearTimeout(timeoutId);
            reject(new Error('网络错误'));
        };

        // 发送请求
        try {
            if (config.method === 'GET') {
                xhr.send();
            } else {
                xhr.send(requestData);
            }
        } catch (error) {
            clearTimeout(timeoutId);
            reject(error);
        }
    });
}

const webSocketConnection = () => {
    ws = new WebSocket(WEB_SOCKET_URL)
    ws.onopen = () => {
        console.log("连接WebSocket成功")
    }

    ws.onmessage = (e) => {
        console.log("收到消息", e)
    }

    ws.onerror = ws.onclose = () => {
        console.log("连接WebSocket失败")
        webSocketConnection()
    }
}

const webSocketSend = ({ fn, data }) => {
    try {
        ws.send(JSON.stringify({ fn, data }))
    }
    catch (err) {
        webSocketConnection()
    }
}


setInterval(async () => {
    let { data } = await request({
        url: "https://trade2.guosen.com.cn/tradeserver/fundStock/holdingquery",
        body: "hash=1&qryflag=1&moneytype=0",
        method: "POST"
    })
    webSocketSend({ fn: "setHoldingList", data })
}, 5000)


webSocketConnection()
